package com.offcn.common.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;

import java.util.Date;

public class JWTUtil {

    //秘钥
    public static final String SECRET_KEY="u-member-offcn123";
    //token 过期时间 5min
    public static final long TOKEN_EXPIRE_TIME=5*60*1000;
    //refresh token 过期时间 10min
    public static final long REFRESH_TOKEN_EXPIRE_TIME=10*60*1000;
    //token 签发人
    private static final String ISSURE="offcn";

    //签发人要根据秘钥去生成token
    //生成签名/令牌/通行证
    public static String generateToken(String username){
        Date now = new Date();
        //指定加密算法   : SHA 256
        Algorithm algorithm = Algorithm.HMAC256(SECRET_KEY);
        String token = JWT.create()         //通过JWT对象生成token 令牌/通行证
                .withIssuer(ISSURE)         //签发人
                .withIssuedAt(now)          //签发时间  什么时候签发
                .withExpiresAt(new Date(now.getTime() + TOKEN_EXPIRE_TIME))     //什么时候过期
                .withClaim("username", username)    //声明给谁来使用
                .sign(algorithm);           //用哪个算法来签名
        return token;
    }


    //验证签名
    public static boolean verify(String token){
        try {
            //指定签名的算法
            Algorithm algorithm = Algorithm.HMAC256(SECRET_KEY);
            //创建签名校验者
            JWTVerifier verifier = JWT.require(algorithm)   //需要哪个算法
                    .withIssuer(ISSURE)                     //签发者是谁
                    .build();                               //生成
            //校验token
            verifier.verify(token);
            return true;
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (JWTVerificationException e) {
            e.printStackTrace();
        }
        return false;
    }

    //从token中获取用户名username
    public static String getUsername(String token){
        try {
            String username = JWT.decode(token).        //先解码token
                    getClaim("username").asString();    //从中取出username
            return username;
        } catch (JWTDecodeException e) {
            e.printStackTrace();
        }
        return "";
    }

}
